<?php

namespace app\beautiful\logic\order;

use app\beautiful\model\appointment\TechnicianModel;
use app\beautiful\model\CouponModel;
use app\beautiful\model\LevelModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberOnceCardItemModel;
use app\beautiful\model\member\MemberOnceCardModel;
use app\beautiful\model\member\MemberProjectModel;
use app\beautiful\model\member\MemberSnapUpModel;
use app\beautiful\model\order\CashierOrderItemModel;
use app\beautiful\model\order\CashierOrderModel;
use app\beautiful\model\order\CashierOrderProjectModel;
use app\beautiful\model\project\ProjectModel;

class OrderCashierLogic
{
    use OrderTrait;
    protected $total_price = 0;
    protected $member_coupon_id;
    protected $num;
    protected $is_vip = false;
    protected $order_item_data = [];
    protected $order_project_data = [];
    protected $once_ids = [];
    protected $snaps = [];
    protected $today;
    protected $coupon_count = 0;
    protected $member_level = [];


    public function createOrder($params)
    {
        //判断用户
        if ($params['member_id'] != 0) {
            $this->checkMember($params['member_id'], false);
            //判断是不是会员
            $member_level = LevelModel::where([
                ['shop_id', '=', $this->shopId],
                ['level_id', '=', $this->member->level_id],
                ['is_delete', '=', 0]
            ])->find();
            if (null !== $member_level) {
                $this->member_level = $member_level->toArray();
                $this->is_vip = true;
            }
        }

        //判断商品
        if (is_array($params) && $params['goods']) {
            foreach ($params['goods'] as $k => $v) {
                $this->checkGoods($v, false, $params);
            }
        }
        //判断项目，以及服务人员
        if (is_array($params) && $params['projects']) {
            foreach ($params['projects'] as $k => $v) {
                $this->checkProjects($v, false, $params);
            }
        }


        //判断总价
        if ($params['total_price']<0) $this->error('计算额不得小于0');


        //获取优惠金额
        $youhui_price = $params['youhui_price'] ?? 0;

        //获取需要支付的金额
        $need_pay = round($params['total_price'] - $youhui_price, 2);
        if ($need_pay < 0) return $this->error('实付款不得小于0');

        if (count($this->order_item_data) ==0 and count($this->order_project_data) == 0){
            return $this->error('商品或项目至少选1组');
        }

        //保存订单
        $order = new CashierOrderModel();
        $order_data = [
            'shop_id' => $this->shopId,
            'member_id' => $params['member_id'],
            'total_num' => $this->num,
            'total_price' => $this->total_price,
            'need_pay' => $need_pay,
            'coupon_money' => $this->coupon_count,
            'youhui_price' => $youhui_price,
            'status' => 1,
        ];
        $order->save($order_data);
        //保存订单商品
        foreach ($this->order_item_data as $k => $v) {
            $this->order_item_data[$k]['order_id'] = $order->order_id;
        }
        $order_item_model = new CashierOrderItemModel();
        $order_item_model->saveAll($this->order_item_data);
//        保存订单项目
        foreach ($this->order_project_data as $k => $v) {
            $this->order_project_data[$k]['order_id'] = $order->order_id;
        }
        $order_project_model = new CashierOrderProjectModel();
        $order_project_model->saveAll($this->order_project_data);

        return $order->order_id;
    }

    public function checkGoods($datas, $lock, $params)
    {
        empty($datas['goods_id']) && $this->error('参数错误#3');
        empty($datas['num']) && $this->error('参数错误#4');
        !array_key_exists('coupon_id', $datas) && $this->error('参数错误#6');
        $this->num = ($this->num ?? 0) + $datas['num'];

        $goods = GoodsModel::where([
            ['shop_id', '=', $this->shopId],
            ['status', '=', 1],
            ['is_delete', '=', 0],
            ['goods_id', '=', $datas['goods_id']]
        ])->field('goods_id,name,cover_img,original_price,vip_price,quota,take_count,fictitious_take_count,is_have_sku')
            ->lock($lock)->find($datas['goods_id']);
        empty($goods) && $this->error('商品不存在');


        $sku_id = isset($datas['sku_id']) ? $datas['sku_id'] : 0;
        $sku_info = [];
        if ($sku_id != 0) {
            $sku_info = GoodsSkuModel::where([
                ['shop_id', '=', $this->shopId],
                ['is_delete', '=', 0],
                ['goods_id', '=', $datas['goods_id']],
                ['sku_id', '=', $sku_id],
                ['quota', '>', $datas['num']]
            ])->field('sku_id,name,original_price,vip_price,quota,take_count')
                ->lock($lock)->find();
            if (null === $sku_info) $this->error($goods->name . '的规格缺货');
        } else {
            if ($goods['quota'] < $datas['num']) $this->error('商品库存不足');
        }

//        优惠券验证
        $coupon_num = $this->checkCoupon($sku_info, $datas['coupon_id'], $params);


        //处理订单商品表
        $price = !empty($sku_info) ? ($this->is_vip ? $sku_info['vip_price'] : $sku_info['original_price']) : ($this->is_vip ? $goods->vip_price : $goods->original_price);
        $this->order_item_data[] = [
            'shop_id' => $this->shopId,
            'goods_id' => $datas['goods_id'],
            'goods_type' => 'normal',
            'goods_name' => $goods->name,
            'goods_cover_img' => $goods->cover_img,
            'goods_sku_id' => $sku_id,
            'coupon_money' => $coupon_num,
            'coupon_id' => $datas['coupon_id'],
            'goods_sku_name' => !empty($sku_info) ? $sku_info['name'] : '',
            'goods_original_price' => isset($sku) ? $sku->original_price : $goods->original_price,
            'goods_price' => $price,
            'goods_num' => $datas['num'],
        ];
        $this->total_price = round((($this->total_price) * 100 + $price * $datas['num'] * 100) / 100, 2);
    }

    public function checkProjects($datas, $lock, $params)
    {
        empty($datas['project_id']) && $this->error('缺少项目id');
        !array_key_exists('type', $datas) && $this->error('参数错误#12');
        $project = ProjectModel::find($datas['project_id']);
        if ($project == null) return $this->error('项目不存在');
        $original_price = $project->market_price;
        if (!array_key_exists('original_price', $datas) && array_key_exists('discount', $this->member_level)) {
            $original_price = $project->market_price * $this->member_level['discount'] / 10;
        }
        $item_info = [
            'shop_id' => $this->shopId,
            'project_id' => $datas['project_id'],
            'price' => array_key_exists('price', $datas) ? $datas['price'] : 0,
            'coupon_id' => array_key_exists('coupon_id', $datas) ? $datas['coupon_id'] : 0,
            'type' => $datas['type'],
            'original_price' => array_key_exists('original_price', $datas) ? $datas['original_price'] : $original_price,
            'technicians' => array_key_exists('technicians', $datas) ? $datas['technicians'] : ''
        ];
        if (array_key_exists('technicians', $datas)) {
            $ids = explode(',', $datas['technicians']);
            if($ids[0] != ''){
                $technician = TechnicianModel::where([['technician_id', 'in', $ids]])->count();
                if (count($ids) != $technician) return $this->error('员工不存在');
            }
        }
        switch ($datas['type']) {
            case 0:
                $name = '项目';
                !array_key_exists('original_price', $datas) && $this->error('项目缺少折后价');
                !array_key_exists('price', $datas) && $this->error('项目缺少需付价');
                $where[] = [];
                $project = ProjectModel::find($datas['project_id']);
                if ($project->shop_id != $this->shopId || $project->is_delete == 1) return $this->error($name . '不存在');
                // 优惠券验证
                $item_info['coupon_money'] = $this->checkCoupon($project, $datas['coupon_id'], $params, 1);
                $item_info['full_name'] = $project->full_name;
                $item_info['market_price'] = $project->market_price;
                $item_info['cover_img'] = $project->cover_img;
                $item_info['abbreviation'] = $project->abbreviation;
                break;
            case 1:
                $member_snap_up_id = $datas['member_snap_up_id'];
                if (in_array($member_snap_up_id, $this->snaps)) return $this->error('请勿重复添加抢购记录');
                $name = '抢购订单';
                if ($params['member_id'] == 0) return $this->error($name . '没有指定用户');
                if ($member_snap_up_id == 0) return $this->error($name . '不存在');
                if (null === $member_snap_up = MemberSnapUpModel::find($member_snap_up_id)) return $this->error($name . '不存在');
                if ($member_snap_up->member_id != $params['member_id']) return $this->error($name . '与用户信息不匹配');
                if ($member_snap_up->shop_id != $this->shopId) return $this->error($name . '不存在');
                if ($member_snap_up->status != 1) return $this->error($name . '的状态不在待消费');
                if ($member_snap_up->valid_end_time < $this->today) return $this->error($name . '已过期2');
                if (null === $member_project = MemberProjectModel::where([
                        ['member_id', '=', $member_snap_up->member_id],
                        ['source', '=', 'snap_up'],
                        ['project_id', '=', $member_snap_up->project_id],
                        ['member_snap_up_id', '=', $member_snap_up_id],
                        ['total_num', '=', $member_snap_up->total_num],
                        ['remain_num', '=', $member_snap_up->remain_num]
                    ])->find()) {
                    return $this->error($name . '不存在4');
                }
                $item_info['full_name'] = $member_snap_up->full_name;
                $item_info['market_price'] = $member_snap_up->market_price;
                $item_info['cover_img'] = $member_snap_up->cover_img;
                $item_info['abbreviation'] = $member_snap_up->abbreviation;
                $item_info['member_snap_up_id'] = $member_snap_up_id;

                $this->snaps[] = $member_snap_up_id;
                break;
            case 2:

                $member_once_card_item_id = $datas['member_once_card_item_id'];
                $name = '次卡订单';
                if ($params['member_id'] == 0) return $this->error($name . '没有指定用户');
                if ($member_once_card_item_id == 0) return $this->error($name . '不存在');
                if (null === $member_once_card_item = MemberOnceCardItemModel::find($member_once_card_item_id)) return $this->error($name . '不存在');
                if ($member_once_card_item->member_id != $params['member_id']) return $this->error($name . '与用户信息不匹配');
                if ($member_once_card_item->shop_id != $this->shopId) return $this->error($name . '不存在');
                if (null === $member_once_card = MemberOnceCardModel::find($member_once_card_item->member_once_card_id)) return $this->error($name . '不存在');
                if ($member_once_card->status != 1) return $this->error($name . '的状态不在待消费');
                if ($member_once_card->valid_end_time < $this->today) return $this->error($name . '已过期');
                if (null === $member_project = MemberProjectModel::where([
                        ['member_id', '=', $member_once_card_item->member_id],
                        ['source', '=', 'once_card'],
                        ['project_id', '=', $member_once_card_item->project_id],
                        ['member_once_card_item_id', '=', $member_once_card_item_id],
                        ['total_num', '=', $member_once_card_item->total_num],
                        ['remain_num', '=', $member_once_card_item->remain_num]
                    ])->find()) {
                    return $this->error($name . '不存在');
                }

                $item_info['full_name'] = $member_once_card_item->full_name;
                $item_info['market_price'] = $member_once_card_item->market_price;
                $item_info['cover_img'] = $member_once_card_item->cover_img;
                $item_info['abbreviation'] = $member_once_card_item->abbreviation;
                $item_info['member_once_card_item_id'] = $member_once_card_item_id;
                $this->snaps[] = $member_once_card_item_id;
                break;
        }


        $this->num++;

        $this->order_project_data[] = $item_info;
        $this->total_price = round((($this->total_price) * 100 + $item_info['original_price'] * 100) / 100, 2);
    }

    /**
     * @param $info 详情（项目，商品）
     * @param $coupon_id 优惠券id
     * @param int $type 0为商品，1为项目
     */
    public function checkCoupon($info, $coupon_id, $params, $type = 0)
    {
        if ($params['member_id'] == 0 || $coupon_id == 0) return 0;
        if (null === $myCoupon = MemberCouponModel::find($coupon_id)) $this->error('优惠券不存在#1');
        if ($myCoupon->status == 1 || $myCoupon->money_limit > $this->total_price) $this->error('该优惠券不可用#2');
        if ($myCoupon->member_id != $params['member_id']) $this->error('该优惠券不可用#3');
        if ($type == 1) {
            $coupon = CouponModel::find($myCoupon->coupon_id);
            if (!in_array($coupon->project_type_id, [0, $info->project_type_id])) return $this->error('该项目不符合类目优惠券');
        }
        $this->coupon_count += $myCoupon->coupon_money;
        return $myCoupon->coupon_money;
    }
}